import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:html_unescape/html_unescape.dart';
import 'package:url_launcher/url_launcher.dart';
import '../components/nba_video_player.dart';

import '../core/nba_models.dart';
import '../core/nba_service.dart';
import 'package:provider/provider.dart';
import '../core/theme_config.dart';

class NbaNewsDetailPage extends StatefulWidget {
  final String newsId;
  final String? title;
  final String? imageUrl;

  const NbaNewsDetailPage({
    super.key,
    required this.newsId,
    this.title,
    this.imageUrl,
  });

  @override
  State<NbaNewsDetailPage> createState() => _NbaNewsDetailPageState();
}

class _NbaNewsDetailPageState extends State<NbaNewsDetailPage> {
  NbaNewsDetail? _newsDetail;
  bool _loading = false;
  bool _error = false;

  @override
  void initState() {
    super.initState();
    _loadNewsDetail();
  }

  Future<void> _loadNewsDetail() async {
    setState(() {
      _loading = true;
      _error = false;
    });

    try {
      final detail = await NbaService.fetchNewsDetail(widget.newsId);
      setState(() {
        _newsDetail = detail;
        _loading = false;
      });
    } catch (e) {
      print('加载新闻详情失败: $e');
      setState(() {
        _loading = false;
        _error = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    final primary = themeConfig.currentPrimaryColor;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primary,
        foregroundColor: Colors.white,
        title: Text(_newsDetail?.title ?? widget.title ?? '新闻详情'),
      ),
      body: _loading
          ? _buildLoadingWidget()
          : _error
              ? _buildErrorWidget()
              : _newsDetail == null
                  ? _buildEmptyWidget()
                  : _buildNewsDetailWidget(),
    );
  }

  Widget _buildLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('正在加载新闻详情...'),
        ],
      ),
    );
  }

  Widget _buildErrorWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, size: 64, color: Colors.red),
          const SizedBox(height: 16),
          const Text('加载失败', style: TextStyle(fontSize: 18)),
          const SizedBox(height: 8),
          Text('新闻ID: ${widget.newsId}', style: const TextStyle(color: Colors.grey)),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadNewsDetail,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.article, size: 64, color: Colors.grey),
          SizedBox(height: 16),
          Text('暂无新闻详情'),
        ],
      ),
    );
  }

  Widget _buildNewsDetailWidget() {
    final detail = _newsDetail!;
    final themeConfig = Provider.of<ThemeConfig>(context);
    return Container(
      decoration: BoxDecoration(gradient: themeConfig.currentGradient),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 1000),
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  detail.title,
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: themeConfig.currentTextColor,
                  ),
                ),
                const SizedBox(height: 16),

                Row(
                  children: [
                    Text(
                      detail.source,
                      style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6)),
                    ),
                    const SizedBox(width: 16),
                    Text(
                      detail.editor,
                      style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6)),
                    ),
                    const SizedBox(width: 16),
                    Text(
                      detail.formattedPublishTime,
                      style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.6)),
                    ),
                  ],
                ),
                const SizedBox(height: 16),

          // 摘要
                if (detail.abstractText.isNotEmpty)
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '摘要:',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: themeConfig.currentTextColor,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        detail.abstractText,
                        style: TextStyle(fontSize: 16, height: 1.6, color: themeConfig.currentTextColor),
                      ),
                      const SizedBox(height: 16),
                    ],
                  ),
                Divider(color: themeConfig.currentTextColor.withOpacity(0.1)),
                const SizedBox(height: 16),
                _buildNewsContent(detail),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 处理文本中的超链接，将URL转换为可点击的链接
  Widget _buildTextWithLinks(String text) {
    final unescape = HtmlUnescape();
    final themeConfig = Provider.of<ThemeConfig>(context);
    String html = unescape.convert(text);

    // 在方法内定义简单的标签清理
    String stripTags(String input) {
      var s = input
          // 换行相关标签转换为换行
          .replaceAll(RegExp(r'<br\s*/?>', caseSensitive: false), '\n')
          .replaceAll(RegExp(r'</?p[^>]*>', caseSensitive: false), '\n');
      // 去除其他HTML标签
      s = s.replaceAll(RegExp(r'<[^>]+>'), '');
      return s;
    }

    // 匹配 HTML 锚点 <a href="...">文本</a>
    // 使用简化模式避免语法问题
    final anchorRegex = RegExp(
      r'<a[^>]*href="([^"]+)"[^>]*>(.*?)<\/a>',
      caseSensitive: false,
    );

    final matches = anchorRegex.allMatches(html);

    if (matches.isEmpty) {
      // 没有锚点时，作为纯文本处理（不显示URL本身）
      return Text(
        stripTags(html),
        style: const TextStyle(fontSize: 16, height: 1.8),
      );
    }

    final textSpans = <TextSpan>[];
    int lastIndex = 0;

    for (final m in matches) {
      // 添加锚点前的普通文本（剥离标签）
      if (m.start > lastIndex) {
        final before = html.substring(lastIndex, m.start);
        final plain = stripTags(before);
        if (plain.isNotEmpty) {
          textSpans.add(TextSpan(text: plain));
        }
      }

      // 锚点：显示名称，点击跳转到 href
      final href = m.group(1) ?? '';
      final labelHtml = m.group(2) ?? '';
      final label = stripTags(labelHtml).trim();

      if (label.isNotEmpty) {
        textSpans.add(
          TextSpan(
            text: label,
            style: TextStyle(
              fontSize: 16,
              height: 1.8,
              color: themeConfig.currentPrimaryColor,
              decoration: TextDecoration.underline,
            ),
            recognizer: TapGestureRecognizer()
              ..onTap = () async {
                final url = href.startsWith('http') ? href : 'https://$href';
                final uri = Uri.parse(url);
                if (await canLaunchUrl(uri)) {
                  await launchUrl(uri);
                }
              },
          ),
        );
      }

      lastIndex = m.end;
    }

    // 添加最后一个锚点后的剩余文本
    if (lastIndex < html.length) {
      final tail = stripTags(html.substring(lastIndex));
      if (tail.isNotEmpty) {
        textSpans.add(TextSpan(text: tail));
      }
    }
    return RichText(
      text: TextSpan(
        style: TextStyle(fontSize: 16, height: 1.8, color: themeConfig.currentTextColor),
        children: textSpans,
      ),
    );
  }

  Widget _buildNewsContent(NbaNewsDetail detail) {
    final unescape = HtmlUnescape();
    // 如果有结构化内容属性，优先使用
    if (detail.contentAttributes.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: detail.contentAttributes.map((attr) {
          switch (attr.itype) {
            case 1: // 文本
              try {
                final content = attr.object['content']?.toString() ?? '';
                //加缩进
                final contents = '    $content';
                //处理content中的超链接
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16),
                  child: _buildTextWithLinks(contents),
                );
              } catch (e) {
                print('解析文本内容失败: $e');
                return const SizedBox.shrink();
              }
            case 2: // 图片
              try {
                final imgurl = attr.object['imgurl']?.toString() ?? '';
                final imageUrl = imgurl.isEmpty ? '' : imgurl;
                if (imageUrl.isEmpty) {
                  return const SizedBox.shrink();
                }
                
                final themeConfig = Provider.of<ThemeConfig>(context);
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16),
                  child: CachedNetworkImage(
                    imageUrl: imageUrl,
                    width: double.infinity,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      height: 200,
                      color: themeConfig.currentTextColor.withOpacity(0.1),
                      child: Icon(Icons.image, color: themeConfig.currentTextColor.withOpacity(0.4)),
                    ),
                    errorWidget: (context, url, error) => Container(
                      height: 200,
                      color: themeConfig.currentTextColor.withOpacity(0.1),
                      child: Icon(Icons.error, color: themeConfig.currentTextColor.withOpacity(0.4)),
                    ),
                  ),
                );
              } catch (e) {
                print('解析图片内容失败: $e');
                return const SizedBox.shrink();
              }
            case 3: // 视频
              try {
                final vid = attr.object['vid']?.toString() ?? '';
                final title = attr.object['title']?.toString() ?? '';
                if (vid.isEmpty) {
                  return const SizedBox.shrink();
                }
                
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16),
                  child: NbaVideoPlayer(
                    vid: vid,
                    title: title,
                    videoData: attr.object, // 传递完整的视频数据对象
                  ),
                );
              } catch (e) {
                print('解析视频内容失败: $e');
                return const SizedBox.shrink();
              }
            default:
              return const SizedBox.shrink();
          }
        }).toList(),
      );
    }
    
    // 如果没有结构化内容，使用HTML内容
    if (detail.contentHtml.isNotEmpty) {
      return _buildTextWithLinks(detail.contentHtml);
    }
    
    return const Text('暂无内容');
  }
}
